# -*- coding: UTF-8 -*-
'''
Created on 2011-8-20

@author: zxz
'''
from flask import Flask, session, request

from datasource import db_session
from sqlalchemy.exc import IntegrityError

from app import app
from friendModel import UserFollow, UserFriend
from user.userModel import User, UserInfo
from common.jsonUtil import success, error

from datetime import datetime

MAX_SIZE = 50
MAX_FOLLOW = 500

@app.route('/friend/', methods=['GET'])
def friend_test():
    return success({'friend' : 'friend test'})

@app.route('/friend/f/<int:fuid>/', methods=['GET'])
def follow(fuid):
    ''' 加关注 '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限')
    fuser = db_session.query(User).filter(User.id == fuid).first()
    if fuser is None:
        return error('601', u'用户不存在')
    cnt = db_session.query(UserFollow).filter(UserFollow.follow==uid).count()
    if cnt > MAX_FOLLOW:
        return error('601', u'已经达到最大关注数')
    follow = UserFollow(fuid, uid, datetime.now())
    try :
        db_session.add(follow)
        db_session.commit()
    except IntegrityError:
        return error('610', u'已经关注')
    ## 检查并添加到friend表
    reverseFollow = db_session.query(UserFollow).filter(UserFollow.uid == uid).filter(UserFollow.follow == fuid).first()
    if reverseFollow is not None:
        ##  需要创建双向关系
        uf1 = UserFriend(uid, fuid, datetime.now())
        db_session.add(uf1)
        db_session.commit()
        uf2 = UserFriend(fuid, uid, datetime.now())
        db_session.add(uf2)
        db_session.commit()
    return success()

@app.route('/friend/f/r/<int:fuid>/', methods=['GET'])
def followRemove(fuid):
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限')
    # 删除关系
    db_session.query(UserFollow).filter(UserFollow.uid == fuid).filter(UserFollow.follow == uid).delete()
    # 删除好友关系
    db_session.query(UserFriend).filter(UserFriend.uid == fuid).filter(UserFriend.follow == uid).delete()
    db_session.query(UserFriend).filter(UserFriend.uid == uid).filter(UserFriend.follow == fuid).delete()
    db_session.commit()
    return success()

@app.route('/friend/f/m/<int:offset>/<int:size>/', methods=['GET'])
def followMeList(offset, size):
    ''' 关注我的fans '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限')
    if size < 1 or size > MAX_SIZE or offset < 0:
        return error('610', u'请求参数错误')
    followers = db_session.query(UserFollow.follower).filter(UserFollow.uid == uid).order_by(UserFriend.gmt_create.desc()).offset(offset).limit(size).all()
    users = db_session.query(UserInfo).filter(UserInfo.uid.in_(followers)).all()
    userEntrys = [u.entry()  for u in users]
    return success({'followers' : userEntrys})

@app.route('/friend/f/m/count/', methods=['GET'])
def followMeCount():
    ''' 关注我的人数量 '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限')
    cnt = db_session.query(UserFollow).filter(UserFollow.uid == uid).count()
    return success({'count' : cnt})

@app.route('/friend/f/o/<int:offset>/<int:size>/', methods=['GET'])
def followOthers(offset, size):
    ''' 关注其他人 '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限')
    if size < 1 or size > MAX_SIZE or offset < 0:
        return error('610', u'请求参数错误')
    followOthers = db_session.query(UserFollow.uid).filter(UserFollow.follower == uid).order_by(UserFollow.gmt_create.desc()).offset(offset).limit(size).all()
    users = db_session.query(UserInfo).filter(UserInfo.uid.in_(followOthers)).all()
    userEntrys = [u.entry() for u in users]
    return success({'users' : userEntrys})

@app.route('/friend/f/o/count/', methods=['GET'])
def followOthersCount():
    ''' 我关注他人的数量 '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限')
    cnt = db_session.query(UserFollow).filter(UserFollow.follow == uid).count()
    return success({'count' : cnt})


@app.route('/friend/myfriends/<int:offset>/<int:size>/', methods=['GET'])
def myFriends(offset, size):
    ''' 获得我的好友(双向关注) '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限')
    if size < 1 or size > MAX_SIZE or offset < 0:
        return error('610', u'请求参数错误')
    fuids = db_session.query(UserFriend.fuid).filter(UserFriend.uid==uid).order_by(UserFriend.gmt_create.desc()).offset(offset).limit(size).all()
    users = db_session.query(UserInfo).filter(UserInfo.uid.in_(fuids)).all()
    userEntrys = [u.entry() for u in users]
    return success({'users' : userEntrys})

@app.route('/friend/myfriends/count/', methods=['GET'])
def myFriendCount():
    ''' 我关注他人的数量 '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限')
    cnt = db_session.query(UserFriend).filter(UserFriend.uid == uid).count()
    return success({'count' : cnt})

@app.route('/friend/st/count/', methods=['GET'])
def followCntInfo():
    ''' 统计关注数量，可取代前面的3个接口 '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限')
    followMecnt = db_session.query(UserFollow).filter(UserFollow.uid == uid).count()
    followOtcnt = db_session.query(UserFollow).filter(UserFollow.follow == uid).count()
    friendCnt = db_session.query(UserFriend).filter(UserFriend.uid == uid).count()
    return success({'followMecnt' : followMecnt, 'followOtcnt' : followOtcnt, 'friendCnt' : friendCnt})

@app.route('/friend/f/common/<int:fuid>/', methods=['GET'])
def commonFollow(fuid):
    ''' 共同关注的人(如某个名人) '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限')
    query_sql = """ select uid from user_follow where follow = :uid and exists (select uid from user_follow where follow = :fuid) """
    common_follows_results = db_session.execute(query_sql, {'uid':uid, 'fuid':fuid})
    common_follows = [rs['uid'] for rs in common_follows_results]
    if common_follows is not None and len(common_follows) > 0:
        users = db_session.query(UserInfo).filter(UserInfo.uid.in_(common_follows))
        userEntrys = [u.entry() for u in users]
        return success({'users' : userEntrys})
    return success()

@app.route('/friend/common/<int:fuid>/', methods=['GET'])
def commonFriend(fuid):
    ''' 共同好友 '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限')
    query_sql = """ select fuid from user_friend where uid = :uid and exists (select fuid from user_friend where uid = :fuid) """
    common_friends_results = db_session.execute(query_sql, {'uid':uid, 'fuid':fuid})
    common_friends = [rs['uid'] for rs in common_friends_results]
    if common_friends is not None and len(common_friends) > 0:
        users = db_session.query(UserInfo).filter(UserInfo.uid.in_(common_friends))
        userEntrys = [u.entry() for u in users]
        return success({'users' : userEntrys})
    return success()

@app.route('/friend/f/s/', methods=['GET'])
def suggest():
    ''' 推荐 '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限')
    # select * from user_info where uid != $ 
    # and uid not in(select follow from user_follow where uid=$) limit 10;
    query_sql = """
                select uid,name,avatar from user_info where uid != :uid
                and uid not in(select follow from user_follow where uid=:uid) limit 10
                """ 
    userInfos = db_session.execute(query_sql, {"uid" : uid}).fetchall()
    # fuids = db_session.query(UserFollow.follow).filter(UserFollow.uid == uid).all()
    # users = db_session.query(UserInfo).filter(UserInfo.uid != uid).filter(not_(UserInfo.uid.in_(fuids))).limit(5)
    baseUsers = [getBaseUsers(userInfo) for userInfo in userInfos]
    return success({'users' : baseUsers})

class BaseUser(object):
    def __init__(self, uid, name, avatar):
        self.uid = uid
        self.name = name
        self.avatar = avatar

def getBaseUsers(resultSet):
    return BaseUser(resultSet['uid'], resultSet['name'], resultSet['avatar'])
